package cn.com.xjnt.vas.ordering.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.frameworks.core.repository.BaseRepository;
import com.frameworks.core.service.AbstractBaseService;
import com.frameworks.utils.PathUtils;

import cn.com.xjnt.vas.ordering.domain.entity.EmployeeInfo;
import cn.com.xjnt.vas.ordering.domain.entity.Hospital;
import cn.com.xjnt.vas.ordering.domain.entity.User;
import cn.com.xjnt.vas.ordering.repository.EmployeeInfoRepository;
import cn.com.xjnt.vas.ordering.repository.UserRepository;
import cn.com.xjnt.vas.ordering.service.EmployeeInfoService;

/** 
* 类说明：
* @author 作者 LUXIN
* @version 创建时间：2016年5月10日18:13:34
*/
@Service
@Transactional
public class EmployeeInfoServiceImpl extends AbstractBaseService<EmployeeInfo, Long> implements EmployeeInfoService {
    private static final Logger logger = LogManager.getLogger(EmployeeInfoServiceImpl.class);
    
    // 初始化附件地址
    private static String photoImgUrl = PathUtils.getWebRootPath() + File.separator + "static" + File.separator
            + "ordering" + File.separator + "photoImg" + File.separator;
    
    @Autowired
    private EmployeeInfoRepository employeeInfoRepository;
    @Autowired
    private UserRepository userRepository;
    @Override
    protected BaseRepository<EmployeeInfo, Long> getBaseRepository() {
        return employeeInfoRepository;
    }

    @Override
    public void save(EmployeeInfo entity) {
        User user = entity.getUser();
        userRepository.save(user);
        entity.setUser(user);
        super.saveOrUpdate(entity);
    }

    @Override
    public void update(EmployeeInfo entity) {
        User user = entity.getUser();
        userRepository.save(user);
        entity.setUser(user);
        super.saveOrUpdate(entity);
    }

    @Override
    public List<EmployeeInfo> findByHospital(Hospital hospital) {
        return employeeInfoRepository.findByHospital(hospital);
    }

    @Override
    public void saveEmployeeInfo(EmployeeInfo model, MultipartFile[] photoImg) {
        try {
            if (photoImg.length != 0) {
                if (photoImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ photoImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(photoImg[0].getInputStream(), photoImgUrl, name);
                    String url = pathToUrl(path);
                    model.setPhotoName(name);
                    model.setPhotoImg(path);
                    model.setPhotoUrl(url);
                }
            }
            this.save(model);
        } catch (IOException e) {
            logger.error("职工照片附件保存至服务器失败：", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void updateEmployeeInfo(EmployeeInfo model, MultipartFile[] photoImg) {
        try {
            if (photoImg.length != 0) {
                if (photoImg[0].getSize() != 0l) {
                    String name = new Date().getTime()+"_"+ photoImg[0].getOriginalFilename();
                    String path = saveFileFromInputStream(photoImg[0].getInputStream(), photoImgUrl, name);
                    String url = pathToUrl(path);
                    model.setPhotoName(name);
                    model.setPhotoImg(path);
                    model.setPhotoUrl(url);
                }
            }
            this.update(model);
        } catch (IOException e) {
            logger.error("职工照片附件保存至服务器失败：", e.getMessage());
            e.printStackTrace();
        } 
    }

    @Override
    public void deleteImg(String path) {
        try {
            deleteFileInServer(path);
        } catch (IOException e) {
            logger.error("从服务器删除职工照片附件失败：", e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 保存文件
     * 
     * @param stream
     * @param path
     * @param filename
     * @throws IOException
     */
    public String saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
        File FileDir = new File(path);
        // 文件路径不存在
        if (!FileDir.isDirectory()) {
            FileDir.mkdirs();
        }

        String dir = path + filename;
        FileOutputStream fs = new FileOutputStream(dir);
        byte[] buffer = new byte[1024 * 1024];
        int byteread = 0;
        @SuppressWarnings("unused")
        int bytesum = 0;
        while ((byteread = stream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
        return dir;
    }

    /**
     * 删除已上传的附件，根据文件真实路径删除
     * 
     * @param url
     * @throws IOException
     */
    public void deleteFileInServer(String url) throws IOException {
        File file = new File(url);
        if (file.exists()) {
            file.delete();
        }
    }
    /**
     * 将真实物理地址转化为web访问地址
     * @param path
     * @return
     */
    public String pathToUrl(String path){
        String url = path.replace("\\","/");
        String temp[] = url.split("vas");
        return temp[1];
    }
}
 